package com.yyj.util.helper;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.yyj.config.RestTemplateConfig;
import com.yyj.constant.WebConstant;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Created by leezp on 2017/8/8.
 */
@Component
public class InvokeHelper {

    private static Logger log = LoggerFactory.getLogger(InvokeHelper.class);

    @Autowired
    RestTemplateConfig restTemplateConfig;

    /**
    /**
     * 构建RestTempate HTTP Header
     *
     * @param paramKey 参数KEY，可以为NULL
     * @param paramValue 参数VALUE
     * @param mediaType
     * @return
     */
    public HttpEntity<String> httpHeaders(String paramKey, Map<String,Object> paramValue,
                                          MediaType mediaType) {
        StringBuilder bodyBuilder = new StringBuilder();
        if (paramValue != null && !paramValue.isEmpty()) {
            if (!StringUtils.isBlank(paramKey)) {
                bodyBuilder.append(paramKey).append("=");
            }
            bodyBuilder.append(JSON.toJSONString(paramValue));
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType((mediaType == null ? MediaType.APPLICATION_JSON : mediaType));
        HttpEntity<String> requestEntity = new HttpEntity<>(bodyBuilder.toString(), headers);
        return requestEntity;
    }

    /**
     * 发送post请求，默认ContentType=application/json;charset=UTF-8
     * @param url
     * @param paramMap
     * @return
     */
    public JSONObject invokePostRequest(String url , Map<String,Object> paramMap){

        log.info("request url : {}", url);
        HttpEntity<String> requestEntity = httpHeaders(null , paramMap , MediaType.APPLICATION_JSON);
        log.info("request body : {}", requestEntity.getBody());

        ResponseEntity<JSONObject> responseEntity = restTemplateConfig.restTemplate().exchange(
                url,
                HttpMethod.POST,
                httpHeaders(null , paramMap , MediaType.APPLICATION_JSON_UTF8),
                JSONObject.class
        );
        log.info("response,status code : {}, body : {}",
                responseEntity.getStatusCode(),
                responseEntity.getBody());

        return responseEntity.getBody();
    }

    public JSONObject invokeRequest(String url , Map<String,Object> paramMap , HttpMethod method){

        log.info("request url : {}", url);
        HttpEntity<String> requestEntity = httpHeaders(null , paramMap , MediaType.APPLICATION_JSON);
        log.info("request body : {}", requestEntity.getBody());

        ResponseEntity<JSONObject> responseEntity = restTemplateConfig.restTemplate().exchange(
                url,
                method,
                httpHeaders(null , paramMap , MediaType.APPLICATION_JSON_UTF8),
                JSONObject.class
        );
        log.info("response,status code : {}, body : {}",
                responseEntity.getStatusCode(),
                responseEntity.getBody());

        return responseEntity.getBody();
    }

    /**
     * 发送post请求，自定义参数请求前缀和ContentType
     * @param url
     * @param paramMap
     * @param paramKey
     * @param method
     * @return
     */
    public JSONObject invokePostRequest(String url , Map<String,Object> paramMap , String paramKey , HttpMethod method){

        log.info("request url : {}", url);
        log.info("request method : {}", method.toString());
        Map<String,Object> paramValue = Maps.newHashMap();
        paramValue.put(paramKey , paramMap);
        paramValue.put(WebConstant.REQUEST_ID , requestIdGenerator());
        paramValue.put("timestamp" , System.currentTimeMillis());
        log.info("request params : {}", paramValue);

        ResponseEntity<JSONObject> responseEntity = restTemplateConfig.restTemplate().exchange(
                url,
                method,
                httpHeaders(null , paramValue , MediaType.APPLICATION_JSON_UTF8),
                JSONObject.class
        );
        log.info("response,status code : {}, body : {}",
                responseEntity.getStatusCode(),
                responseEntity.getBody());

        return responseEntity.getBody();
    }

    /**
     * 封装服务调用请求通用参数，发送POST请求
     * @param url
     * @param paramMap
     * @return
     */
    public JSONObject postForJson(String url , Map<String,Object> paramMap) {
        paramMap.put(WebConstant.REQUEST_ID , requestIdGenerator());
        paramMap.put("timestamp" , System.currentTimeMillis());
        return invokePostRequest(url , paramMap);
    }

    /**
     * 封装服务调用请求通用参数，发送POST请求
     * @param url
     * @param dataParams
     * @param pageParams
     * @return
     */
    public JSONObject postForJson(String url , Map<String,Object> dataParams , Map<String,Object> pageParams) {
        Map paramMap = Maps.newHashMap();
        paramMap.put(WebConstant.REQUEST_ID , requestIdGenerator());
        paramMap.put("timestamp" , System.currentTimeMillis());
        paramMap.put("data" , dataParams);
        paramMap.put("page" , pageParams);
        return invokePostRequest(url , paramMap);
    }


    /**
     * 判断接口返回是否成功
     *
     * */
    public boolean checkRsp(JSONObject jsonRsp){
        int returnCode = jsonRsp.getIntValue("rc");
        return  0 < returnCode
                && WebConstant.HTTP_CODE_400 != returnCode
                && WebConstant.HTTP_CODE_302 != returnCode
                && WebConstant.HTTP_CODE_404 != returnCode
                && WebConstant.HTTP_CODE_500 != returnCode
                && WebConstant.HTTP_CODE_502 != returnCode
                && WebConstant.HTTP_CODE_504 != returnCode
                ? true : false ;
    }

    /**
     * requestId生成
     * @return
     */
    public String requestIdGenerator(){
        return "guess-weixin-service-" + System.currentTimeMillis();
    }
}
